const user = require("../models/userDetail")
const menu = require("../models/menu")
const point = require("../models/point")
const records = require('../models/records')

var express = require('express');
var router = express.Router();

const formidable = require('formidable');

//返回图片
router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            user.find({
                flags: {
                    $all: fields.flags
                }
            }, {
                // process: 1
                UUID: 1
            }, (err, students) => {
                let stu_num = students.length
                // console.log("students: " + students.length)
                if (err) {
                    res.json({ 'state': false, 'msg': err });
                } else {
                    if(students.length===0){
                        res.json({'state':false, 'msg':'未找到相应学生'});
                    }else{
                        let uuid_list = students.map((ele) => {
                            return ele.UUID
                        })
                        records.find({
                            UUID: {
                                $in: uuid_list
                            }
                        }, (err, results) => {
                            if(err) {
                                res.json({'state' : false, 'msg': '查找记录出错！'})
                            }else {
                                // console.log("记录个数：" + results.length);
                                let find_menu = () => {
                                    return new Promise(function (resolve, reject) {
                                        menu.find({}, (err, menu) => {
                                            // console.log("menu: " + menu.length)
                                            if (err) {
                                                res.json({ 'state': false, 'msg': err });
                                            } else {
                                                resolve(menu)
                                            }
                                        })
                                    })
                                }

                                let find_points = (menu) => {
                                    return new Promise(function (resolve, reject) {
                                        point.find({}, {
                                            _id: 1,
                                            menu: 1,
                                            seq: 1,
                                            title: 1,
                                        }, { sort: [[['_id', 1]]] }, (err, points) => {
                                            // console.log("points: " + points.length)
                                            if (err) {
                                                res.json({ 'state': false, 'msg': err });
                                            } else {
                                                resolve({ menu, points })
                                            }
                                        })
                                    })
                                }
                                let return_data = ({ menu: menus, points }) => {
                                    let data = {}
            
                                    menus.forEach(menu => {
                                        menu.menu.forEach((item, m) => {
                                            if (!data[menu.lesson]) data[menu.lesson] = [];
                                            data[menu.lesson].push({
                                                title: item.title,
                                                subtitle: []
                                            })
                                            item.subtitle.forEach((name, k) => {
                                                data[menu.lesson][m].subtitle.push({
                                                    name: name,
                                                    point_list: sort_point(points.filter(item => {
                                                        return item.menu == menu.lesson + ',' + m + "," + k
                                                    }))
                                                })
                                            })
                                        })
                                    });
                                    // console.log('date',data.js[0].subtitle[0].point_list)
                                    
                                    results.forEach(re => {
                                        let tmp = re.menu.split(',');
                                        let lesson = tmp[0];
                                        let chara_num = parseInt(tmp[1]);
                                        let section_num = parseInt(tmp[2]);
                                        let point_seq = re.seq;
                                        let point_ID = re.point_ID;
                                        if(lesson === 'js') {
                                            data.js[chara_num].subtitle[section_num].point_list.forEach((ele, k) => {
                                                if(ele.point_id == point_ID){
                                                    let index = data.js[chara_num].subtitle[section_num].point_list[k].UUID_list.indexOf(re.UUID)
                                                    // console.log(index)
                                                    if(index===-1){
                                                        data.js[chara_num].subtitle[section_num].point_list[k].answer_num++;
                                                        data.js[chara_num].subtitle[section_num].point_list[k].UUID_list.push(re.UUID)
                                                    }
                                                }
                                            })
                                        }else if(lesson === 'wx'){
                                            data.wx[chara_num].subtitle[section_num].point_list.forEach((ele, k) => {
                                                if(ele.point_id == point_ID){
                                                    let index = data.wx[chara_num].subtitle[section_num].point_list[k].UUID_list.indexOf(re.UUID)
                                                    // console.log(index)
                                                    if(index===-1){
                                                        data.wx[chara_num].subtitle[section_num].point_list[k].answer_num++;
                                                        data.wx[chara_num].subtitle[section_num].point_list[k].UUID_list.push(re.UUID)
                                                    }
                                                }
                                            })
                                        }else if(lesson === 'ydhlw') {
                                            data.ydhlw[chara_num].subtitle[section_num].point_list.forEach((ele, k) => {
                                                if(ele.point_id == point_ID){
                                                    let index = data.ydhlw[chara_num].subtitle[section_num].point_list[k].UUID_list.indexOf(re.UUID)
                                                    // console.log(index)
                                                    if(index===-1){
                                                        data.ydhlw[chara_num].subtitle[section_num].point_list[k].answer_num++;
                                                        data.ydhlw[chara_num].subtitle[section_num].point_list[k].UUID_list.push(re.UUID)
                                                    }
                                                }
                                            })
                                        }
                                    })
                                    
                                    let dataToReturn_js = []
                                    let dataToReturn_wx = []
                                    let dataToReturn_ydhlw = []
                                    for (let w = 0; w < data.js.length; w++) {
                                        for (let e = 0; e < data.js[w].subtitle.length; e++) {
                                            for (let s = 0; s < data.js[w].subtitle[e].point_list.length; s++) {
                                                data.js[w].subtitle[e].point_list[s].percent = parseFloat((data.js[w].subtitle[e].point_list[s].answer_num / stu_num *100).toFixed(2)) 
                                            } 
                                            dataToReturn_js.push.apply(dataToReturn_js, data.js[w].subtitle[e].point_list);
                                        }
                                    }
                                    for (let w = 0; w < data.wx.length; w++) {
                                        for (let e = 0; e < data.wx[w].subtitle.length; e++) {
                                            for (let s = 0; s < data.wx[w].subtitle[e].point_list.length; s++) {
                                                data.wx[w].subtitle[e].point_list[s].percent = parseFloat((data.wx[w].subtitle[e].point_list[s].answer_num / stu_num *100).toFixed(2)) 
                                            } 
                                            dataToReturn_wx.push.apply(dataToReturn_wx, data.wx[w].subtitle[e].point_list);
                                        }
                                    }

                                    for (let w = 0; w < data.ydhlw.length; w++) {
                                        for (let e = 0; e < data.ydhlw[w].subtitle.length; e++) {
                                            for (let s = 0; s < data.ydhlw[w].subtitle[e].point_list.length; s++) {
                                                    data.ydhlw[w].subtitle[e].point_list[s].percent = parseFloat((data.ydhlw[w].subtitle[e].point_list[s].answer_num / stu_num*100).toFixed(2)) 
                                            } 
                                            dataToReturn_ydhlw.push.apply(dataToReturn_ydhlw, data.ydhlw[w].subtitle[e].point_list);
                                        }
                                    }
                                    res.json({
                                        state: true,
                                        js: dataToReturn_js,
                                        wx: dataToReturn_wx,
                                        ydhlw: dataToReturn_ydhlw
                                    })
                                }
            
                                let sort_point = (raw_list) => {
                                    if (raw_list.length == 0) return []
            
                                    let sorted_list = [raw_list[0]]
            
                                    for (let i = 1; i < raw_list.length; i++) {
                                        if (raw_list[i].seq > sorted_list[i - 1].seq) {
                                            sorted_list.push(raw_list[i]);
                                        } else {
                                            for (let j = 0; j < sorted_list.length; j++) {
                                                if (sorted_list[j].seq + 1 === raw_list[i].seq) {
                                                    sorted_list.splice(j + 1, 0, raw_list[i]);
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    return sorted_list.map((ele) => {
                                        return {
                                            name: ele.title,
                                            point_id: ele._id,
                                            answer_num: 0,
                                            percent: 0,
                                            UUID_list: []
                                        }
                                    })
                                }
            
                                find_menu().then(find_points).then(return_data)
                            }
                        })
                    }
                }
            })
        }

    });

});

module.exports = router;



// data.js.push( { 
//     title: '已学完本课程', 
//     subtitle:[{ 
//         name: '已学完本课程',
//         point_title: [ { 
//             name: '已学完本课程',
//             point_id: '',
//             number: 0,
//             percent: 0
//         } ] 
//     }]
// })
// data.wx.push( { 
//     title: '已学完本课程', 
//     subtitle:[{ 
//         name: '已学完本课程',
//         point_title: [ { 
//             name: '已学完本课程',
//             point_id: '',
//             number: 0,
//             percent: 0
//         } ] 
//     }]
// })
// data.ydhlw.push( { 
//     title: '已学完本课程', 
//     subtitle:[{ 
//         name: '已学完本课程',
//         point_title: [ { 
//             name: '已学完本课程',
//             point_id: '',
//             number: 0,
//             percent: 0
//         } ] 
//     }]
// })
// console.log(data.js[4].subtitle[0].point_title)
                                        
                                        
// let temp1 = st.process[1][0].split(",")
// let wx_chapter = parseInt(temp1[1])
// let wx_section = parseInt(temp1[2])
// let wx_point = st.process[1][2]

// let temp2 = st.process[2][0].split(",")
// let ydhlw_chapter = parseInt(temp2[1])
// let ydhlw_section = parseInt(temp2[2])
// let ydhlw_point = st.process[2][2]

//(js,4,0)表示学完所有课程
// if (js_chapter >= 0 && js_chapter<4) {
//     let js_targetlist = data.js[js_chapter].subtitle[js_section].point_title.filter((item) => {
//         return item.point_id == js_point
//     })
//     if(js_targetlist.length!==0){
//         let js_target = js_targetlist[0];
//         let js_target_index = data.js[js_chapter].subtitle[js_section].point_title.indexOf(js_target)
//         data.js[js_chapter].subtitle[js_section].point_title[js_target_index].number++
//     }
// } else if (js_chapter === 4) {
//     data.js[4].subtitle[0].point_title[0].number++
// }

// if (wx_chapter >= 0 && wx_chapter<4) {
//     let wx_targetlist = data.wx[wx_chapter].subtitle[wx_section].point_title.filter((item) => {
//         return item.point_id == wx_point
//     })
//     if(wx_targetlist.length!==0){
//         let wx_target = wx_targetlist[0];
//         let wx_target_index = data.wx[wx_chapter].subtitle[wx_section].point_title.indexOf(wx_target)
//         data.wx[wx_chapter].subtitle[wx_section].point_title[wx_target_index].number++
//     }
// } else if (wx_chapter === 4) {
//     data.wx[4].subtitle[0].point_title[0].number++
// }

// if (ydhlw_chapter >= 0 && ydhlw_chapter<3) {
//     let ydhlw_targetlist = data.ydhlw[ydhlw_chapter].subtitle[ydhlw_section].point_title.filter((item) => {
//         return item.point_id == ydhlw_point
//     })
//     if(ydhlw_targetlist.length!==0){
//         let ydhlw_target = ydhlw_targetlist[0];
//         let ydhlw_target_index = data.ydhlw[ydhlw_chapter].subtitle[ydhlw_section].point_title.indexOf(ydhlw_target)
//         data.ydhlw[ydhlw_chapter].subtitle[ydhlw_section].point_title[ydhlw_target_index].number++
//     }
// } else if (ydhlw_chapter === 3) {
//     data.ydhlw[3].subtitle[0].point_title[0].number++
// }